package example2;

import common.ListNode;
import utils.ListNodeUtil;

import java.util.ArrayList;
import java.util.List;

//148. 排序链表
public class LeetCode148 {
    public static void main(String[] args) {
        Integer[] arr = {4,2,1,3};
        ListNode head = ListNodeUtil.transformArrayToListNode(arr);
        new Solution148_3().sortList(head);
    }
}

/**
 * 方法三：自底向上的归并排序
 * 时间复杂度O(n log n)
 */
class Solution148_3 {
    public ListNode sortList(ListNode head) {
        if (head == null) {
            return head;
        }
        int length = 0;
        ListNode node = head;
        while (node != null) {
            length++;
            node = node.next;
        }
        ListNode dummyHead = new ListNode(0, head);
        for (int subLength = 1; subLength < length; subLength <<= 1) {
            ListNode prev = dummyHead, curr = dummyHead.next;
            while (curr != null) {
                ListNode head1 = curr;
                for (int i = 1; i < subLength && curr.next != null; i++) {
                    curr = curr.next;
                }
                ListNode head2 = curr.next;
                curr.next = null;
                curr = head2;
                for (int i = 1; i < subLength && curr != null && curr.next != null; i++) {
                    curr = curr.next;
                }
                ListNode next = null;
                if (curr != null) {
                    next = curr.next;
                    curr.next = null;
                }
                ListNode merged = merge(head1, head2);
                prev.next = merged;
                while (prev.next != null) {
                    prev = prev.next;
                }
                curr = next;
            }
        }
        return dummyHead.next;
    }

    public ListNode merge(ListNode head1, ListNode head2) {
        ListNode dummyHead = new ListNode(0);
        ListNode temp = dummyHead, temp1 = head1, temp2 = head2;
        while (temp1 != null && temp2 != null) {
            if (temp1.val <= temp2.val) {
                temp.next = temp1;
                temp1 = temp1.next;
            } else {
                temp.next = temp2;
                temp2 = temp2.next;
            }
            temp = temp.next;
        }
        if (temp1 != null) {
            temp.next = temp1;
        } else if (temp2 != null) {
            temp.next = temp2;
        }
        return dummyHead.next;
    }
}

/**
 * 方法二：自顶向下的归并排序，先找到链表的中间节点，然后将链表分为两部分，然后分别将两部分排序再合并，递归进行
 * 时间复杂度O(n log n)      空间复杂度O(log n)
 */
class Solution148_2 {
    public ListNode sortList(ListNode head) {
        return sort(head,null);
    }

    public ListNode sort(ListNode begin,ListNode end){
        if(begin == null || begin == end)    return begin;
        if(begin.next == end){
            begin.next = null;
            return begin;
        }
        ListNode slow = begin;
        ListNode fast = begin;
        while(fast != end){
            slow = slow.next;
            fast = fast.next;
            if(fast != end){
                fast = fast.next;
            }
        }
        ListNode mid = slow;
        ListNode left = sort(begin,mid);
        ListNode right = sort(mid,end);
        return mergeListNode(left,right);
    }

    //合并两个有序链表
    public ListNode mergeListNode(ListNode headA,ListNode headB){
        ListNode a = headA;
        ListNode b = headB;
        ListNode newHead = new ListNode(0);
        ListNode temp = newHead;
        while(a != null && b != null){
            if(a.val <= b.val){
                temp.next = a;
                a = a.next;
            }else{
                temp.next = b;
                b = b.next;
            }
            temp = temp.next;
        }
        if(a != null){
            temp.next = a;
        }
        if(b != null){
            temp.next = b;
        }
        return newHead.next;
    }

    //交换两个节点的值
    public void swapVal(ListNode a,ListNode b){
        int temp = a.val;
        a.val = b.val;
        b.val = temp;
    }
}


/**
 * 方法一：转换成数组排序，这里用的堆排序
 * 时间复杂度 O(n log n)     空间复杂度 O(n)
 */
class Solution148_1 {
    public ListNode sortList(ListNode head) {
        if(head == null)    return null;
        //将链表转换为数组
        ListNode node = head;
        List<Integer> list = new ArrayList<>();
        while(node != null){
            list.add(node.val);
            node = node.next;
        }
        int[] arr = new int[list.size()];
        for(int i=0;i<list.size();i++){
            arr[i] = list.get(i);
        }
        heapSort(arr);
        ListNode result = new ListNode();
        node = result;
        for(int i=0;i<arr.length;i++){
            node.val = arr[i];
            if(i != arr.length - 1){
                node.next = new ListNode();
                node = node.next;
            }
        }
        return result;
    }

    public void heapSort(int[] arr){
        int n = arr.length;
        //调整每个非叶子节点，从而变成大根堆
        for(int i=n/2-1;i>=0;i--){
            heapify(arr,n,i);
        }
        //遍历，每次都将顶点也就是当前排序序列中的最大值放到当前序列的最后，从而排成从小到大的顺序
        for(int i=n-1;i>=0;i--){
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;
            //交换顺序后继续调整堆
            heapify(arr,i,0);
        }
    }

    //调整堆，调整某个节点的子树
    public void heapify(int[] arr,int n,int i){
        int largest = i;
        int left = 2 * i + 1;
        int right = 2 * i + 2;
        //左孩子存在，且左孩子的数值大于当前指向节点（即父节点）
        if(left < n && arr[left] > arr[largest]){
            largest = left;
        }
        //右孩子存在，且右孩子的数值大于当前指向节点（如果上个条件不满足，这里就是父节点，如果满足就是左孩子）
        if(right < n && arr[right] > arr[largest]){
            largest = right;
        }

        //如果父节点不是最大值
        if(i != largest){
            int temp = arr[i];
            arr[i] = arr[largest];
            arr[largest] = temp;

            //largest是交换过的节点，要校验并调整这个节点的子树
            heapify(arr,n,largest);
        }
    }
}
